package de.koo.grum.controllers

import de.koo.grum.domain.*

class UserController {
    
    def index = { redirect(action:list,params:params) }

    // the delete, save and update actions only accept POST requests
    def static allowedMethods = [delete:'POST', save:'POST', update:'POST']

    def list = {
        //if(!params.max) params.max = 50
        def users
        def searchString=""
        
        if(params.searchString) {
        	searchString=params.searchString

        	def c = User.createCriteria()
        	users = c { 
        		or { like("firstname","%${searchString}%")
        			like("lastname","%${searchString}%")
        			like("username","%${searchString}%") 
        		}
        	}
        }
        else {
        	users=User.list(params)
        }
        
        [ userList: users, searchString:searchString, resultSize:users.size(), pageSize:50 ]
    }

    def login = {}

    def doLogin = {
        def user=User.findByUsernameAndPassword(params.username,params.password)
        if (user) {
                //session=request.getSession()
                session.user=user
                flash.message="login successful."
                redirect(action:list)
        }
        else {
                flash.message="Username or password are invalid."
                render(view:'login',model:[user:user])
        }
    }

    def doLogout = {
        session.invalidate()    
                redirect(action:login,params:params)
    }

    def show = {
        def user = User.get( params.id )

        if(user) {
        	return [ user : user ]
        }
        else { 
        	flash.message = "User not found with id ${params.id}"
            redirect(action:list) 
        }
    }

    def delete = {
        def user = User.get( params.id )
        if(user) {
            user.delete(flush:true)
            flash.message = "User ${params.id} deleted"
            redirect(action:list)
        }
        else {
            flash.message = "User not found with id ${params.id}"
            redirect(action:list)
        }
    }

	def edit = {
        def user = User.get( params.id )

        if(!user) {
            flash.message = "User not found with id ${params.id}"
            redirect(action:list)
        }
        else {
        	def availableGroups=Group.list(order:'asc')
        	def userGroups=user.groups
        	availableGroups=availableGroups-userGroups
        	
            return [ user : user, address : user.address, availableGroups: availableGroups ]
        }
    }

    def update = {
        def user = User.get( params.id )
        def address = null
        
        if(user) {
             user.properties = params

        	 if (user.address) {
        	 	address = Address.get(user.address.id)
		        address.city = params.city
		        address.street = params.street
		        address.zipcode = Long.parseLong(params.zipcode)

		        user.address=address         	 	
        	 }
            if(address.validate() && user.validate()) {
            	address.save(flush:true)
            	user.save(flush:true)
                flash.message = "User ${params.id} updated."
                redirect(action:show,id:user.id)
            }
            else {
            	user.errors.allErrors.each {log.error(it)}
                render(view:'edit',model:[user:user])
            }
        }
        else {
            flash.message = "User not found with id ${params.id}"
            redirect(action:edit,id:params.id)
        }
    }

    def create = {
        def user = new User()
        user.properties = params
        return ['user':user]
    }

    def save = {
        def user = new User()
        user.properties = params
        
        Address address = new Address()
        address.city = params.city
        address.street = params.street
        address.zipcode = Long.parseLong(params.zipcode)
        user.address=address 
        
        if(address.validate() && user.validate()) {
        	address.save(flush:true)
        	user.save(flush:true)
            flash.message = "User ${user.id} created."
            redirect(action:edit,id:user.id)
        }
        else {
            user.errors.allErrors.each {log.error(it)}
            render(view:'create',model:[user:user])
        }
    }

    def addGroup = {
        def user = User.get( params.id )
        if(user) {
        	Group group=Group.get(params.group_id)
        	if (group) {
                group.addToUsers(user)
                if(group.save(flush:true)){
                	flash.message = "Group ${params.group_id} added."
                }
                else {
                	flash.message = "Could not add Group ${params.group_id}."	                	
                }
        	}
            redirect(action:edit,id:user.id)
        }
        else {
            flash.message = "User not found with id ${params.id}"
            redirect(action:list)
        }
    }

    def deleteGroup = {
        def user = User.get( params.id )
        if(user) {
        	def group=Group.get(params.group_id)
        	if (group) {
                group.users.remove(user)
                if(group.save(flush:true)){
                	flash.message = "Group ${params.group_id} deleted."
                }
                else {
                	flash.message = "Could not delete Group ${params.group_id}."	                	
                }
        	}
            redirect(action:edit,id:user.id)
        }
        else {
            flash.message = "User not found with id ${params.id}"
            redirect(action:list)
        }
    }

    def deleteContactData = {
        def user = User.get( params.id )
        if(user) {
        	def cd=ContactData.get(params.ContactData.id)
        	if (cd) {
                user.contactData.remove(cd)
                if(user.save(flush:true)){
                	cd.delete(flush:true)
                	flash.message = "Contact Data ${params.ContactData.id} deleted."
                }
                else {
                	flash.message = "Could not delete Contact Data ${params.ContactData.id}."	                	
                }
        	}
            redirect(action:edit,id:user.id)
        }
        else {
            flash.message = "User not found with id ${params.id}"
            redirect(action:list)
        }
    }

    def upload = {
        def user = User.get( params.id )

        if(user) {
            //handle uploaded file
            def uploadedFile = request.getFile('image')
            if(!uploadedFile.empty){
                if(log.isErrorEnabled()){
                    log.error "Class: ${uploadedFile.class}"
                    log.error "Name: ${uploadedFile.name}"
                    log.error "OriginalFileName: ${uploadedFile.originalFilename}"
                    log.error "Size: ${uploadedFile.size}"
                    log.error "ContentType: ${uploadedFile.contentType}"
                }

                def webRootDir = servletContext.getRealPath("/")
                def userDir = new File(webRootDir, "/images/users/${user.username}")
                userDir.mkdirs()
                uploadedFile.transferTo( new File( userDir, uploadedFile.originalFilename))
                user.imagename = uploadedFile.originalFilename

                if(user.validate()) {
                    user.save(flush:true)
                    flash.message = "Image uploaded."
                    redirect(action:show,id:user.id)
                }
                else {
                    user.errors.allErrors.each {log.error(it)}
                    render(view:'edit',model:[user:user])
                }
            }
            else {
                flash.message = "Upload not successful"
                redirect(action:edit,id:params.id)
            }
        }
        else {
            flash.message = "User not found with id ${params.id}"
            redirect(action:edit,id:params.id)
        }
    }
}